import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { FormInstance } from 'antd/lib/form';
import { Modal, Button, Form, message, Input, DatePicker, Select, InputNumber, Space } from 'antd';
import PropTypes from 'prop-types';
import moment, { Moment } from 'moment';
import { debounce, range } from 'lodash';
import { DATE_HMS } from '@/support/constant/common';
const { RangePicker } = DatePicker;

const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  vehicleConditionDataDownload: state.vehicleConditionDataDownload,
});
class _AddModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();
  rangeRef = React.createRef<FormInstance>();

  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      dataClassOpt: [],
      dates: [],
      today: moment(),
      selectTimeStart: undefined,
      selectTimeEnd: undefined,
    };
  }

  componentDidUpdate(prevProps: any) {
    const { modalVisible, formData } = this.props;
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      const today = moment();
      const initTimes = [moment(today).subtract(1, 'days'), today];
      this.formRef &&
        this.formRef.current?.setFieldsValue({
          ...formData,
          timeRange: initTimes,
          selectTimeStart: initTimes[0],
          selectTimeEnd: initTimes[1],
        });
      this.setState({
        today: today,
        dates: initTimes,
        selectTimeStart: initTimes[0],
        selectTimeEnd: initTimes[1],
      });
    }
  }
  componentDidMount(): void {
    this.getDataClassOpt();
  }
  handleSubmit = () => {
    this.formRef.current?.submit();
  };

  onFinish = (values: any) => {
    const { dispatch } = this.props;
    const { dataClassOpt } = this.state;
    let postData = {
      vin: values.vin,
      dataClass: values.dataClass,
      selectTimeStart: values.selectTimeStart.format(DATE_HMS),
      selectTimeEnd: values.selectTimeEnd.format(DATE_HMS),
      brand: dataClassOpt.find(t => t.value === values.dataClass).brand,
    };
    let dType = 'vehicleConditionDataDownload/postObjWithRes';
    let url = '/vehicletask/add'; //新增
    this.setState({
      loading: true,
    });
    dispatch({
      type: dType,
      payload: {
        url: url,
        ...postData,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('创建成功');
          this.close('add');
        }
        this.setState({
          loading: false,
        });
      },
    });
  };

  close = (refresh = false as string | boolean) => {
    const { closeModal } = this.props;
    this.setState({ dates: undefined, selectTimeStart: undefined, selectTimeEnd: undefined });
    this.formRef.current && this.formRef.current.resetFields();
    closeModal(refresh);
  };
  getDataClassOpt = debounce((v = '') => {
    const { dispatch } = this.props;
    const params = {
      number: 1,
      size: 9999,
      dataClass: v,
    };
    dispatch({
      type: 'vehicleConditionDataDownload/postObjWithRes',
      payload: { url: '/dataclass/list', ...params },
      callback: res => {
        if (res.statusCode === '0') {
          this.setState({
            dataClassOpt: (res.data?.content ?? []).map(t => ({
              label: t.dataClass,
              value: t.dataClass,
              brand: t.brand,
            })),
          });
        } else {
          this.setState({ dataClassOpt: [] });
        }
      },
    });
  }, 100);
  disabledDateStart = (current: Moment) => {
    const currentStart = current.clone().startOf('day');
    const { today } = this.state;
    const dates = [
      this.state.selectTimeStart?.clone().startOf('day'),
      this.state.selectTimeEnd?.clone().startOf('day'),
    ];
    const rangeDays = currentStart.diff(today, 'days');
    if (rangeDays > 30 || rangeDays <= -30) return true;

    const num = 1 * 24 * 60 * 60 * 1000;
    // const tooEarly = dates[1] && dates[1].diff(currentStart) > num;
    const tooLate = dates[1] && currentStart.diff(dates[1]) > 0;
    return !!tooLate;
  };
  disabledDateEnd = (current: Moment) => {
    const currentStart = current.clone().startOf('day');
    const { today } = this.state;
    const dates = [
      this.state.selectTimeStart?.clone().startOf('day'),
      this.state.selectTimeEnd?.clone().startOf('day'),
    ];
    const rangeDays = currentStart.diff(today, 'days');
    if (rangeDays > 30 || rangeDays <= -30) return true;

    const num = 1 * 24 * 60 * 60 * 1000;

    const tooEarly = dates[0] && dates[0].diff(currentStart) > 0;
    // const tooLate = dates[0] && currentStart.diff(dates[0]) > num;
    return !!tooEarly;
  };
  disabledTimeStart = date => {
    const endTime = this.state.selectTimeEnd;
    const num = 1 * 24 * 60 * 60 * 1000;
    return {
      disabledHours: () =>
        range(0, 24).filter(n => endTime && moment(endTime).diff(moment(date).hour(n)) < 0),
      disabledMinutes: () =>
        range(0, 60).filter(n => endTime && moment(endTime).diff(moment(date).minute(n)) < 0),
      disabledSeconds: () =>
        range(0, 60).filter(n => endTime && moment(endTime).diff(moment(date).second(n)) < 0),
    };
  };
  disabledTimeEnd = date => {
    const startTime = this.state.selectTimeStart;
    const num = -1 * 24 * 60 * 60 * 1000;
    return {
      disabledHours: () =>
        range(0, 24).filter(n => startTime && moment(startTime).diff(moment(date).hour(n)) > 0),
      disabledMinutes: () =>
        range(0, 60).filter(n => startTime && moment(startTime).diff(moment(date).minute(n)) > 0),
      disabledSeconds: () =>
        range(0, 60).filter(n => startTime && moment(startTime).diff(moment(date).second(n)) > 0),
    };
  };
  onValuesChange = changedValues => {
    const key = Object.keys(changedValues)[0];
    if (['selectTimeStart', 'selectTimeEnd'].includes(key)) {
      const { selectTimeStart, selectTimeEnd } = this.state;
      this.setState(changedValues);
      if (
        key === 'selectTimeStart' &&
        selectTimeEnd &&
        moment(changedValues.selectTimeStart).diff(selectTimeEnd) > 0
      ) {
        this.setState({ selectTimeEnd: changedValues.selectTimeStart });
        this.formRef.current?.setFieldsValue({
          selectTimeEnd: changedValues.selectTimeStart,
        });
      } else if (
        key === 'selectTimeEnd' &&
        selectTimeStart &&
        moment(selectTimeStart).diff(changedValues.selectTimeEnd) > 0
      ) {
        this.setState({ selectTimeStart: changedValues.selectTimeEnd });
        this.formRef.current?.setFieldsValue({
          selectTimeStart: changedValues.selectTimeStart,
        });
      }
    }
  };
  render() {
    const { formData, modalVisible } = this.props;
    const { loading, dataClassOpt } = this.state;
    const footer = (
      <div>
        <Button size="small" onClick={() => this.close()}>
          取消
        </Button>
        <Button size="small" loading={loading} onClick={this.handleSubmit} type="primary">
          确定
        </Button>
      </div>
    );
    let title = '创建任务';

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: {
          span: 6,
          // offset: 4,
        },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: {
          span: 14,
        },
        md: { span: 16 },
      },
    };

    return (
      <Modal
        title={title}
        footer={footer}
        visible={modalVisible}
        width={700}
        onCancel={() => this.close()}
      >
        <Form
          onValuesChange={this.onValuesChange}
          style={{ marginTop: 12 }}
          ref={this.formRef}
          onFinish={this.onFinish}
        >
          <FormItem
            {...formItemLayout}
            label="VIN码"
            colon={false}
            name="vin"
            rules={[
              {
                required: true,
                whitespace: true,
                message: '请输入VIN码',
              },
            ]}
          >
            <Input placeholder="请输入VIN码" maxLength={30} />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="数据分类"
            colon={false}
            name="dataClass"
            rules={[{ required: true, whitespace: true, message: '请输入数据分类' }]}
          >
            <Select
              optionFilterProp="label"
              // onSearch={this.getDataClassOpt}
              showSearch
              allowClear
              options={dataClassOpt}
              placeholder="请选择数据分类"
            />
          </FormItem>
          {/* <FormItem
            {...formItemLayout}
            label="查询时间"
            colon={false}
            name="timeRange"
            rules={[
              {
                required: true,
                validator: (rule, value, callback) => {
                  if (!value) callback('请选择时间');
                  callback();
                },
              },
            ]}
          >
            <RangePicker
              allowClear
              placeholder={['开始时间', '结束时间']}
              style={{ width: '100%' }}
              disabledDate={this.disabledDate}
              onCalendarChange={val => this.setState({ dates: val })}
              format={DATE_HMS}
              showTime={{ format: DATE_HMS }}
              getCalendarContainer={trigger => trigger.parentNode}
              onPanelChange={v => {
                console.log('🚀 ~ _AddModal ~ render ~ v:', v);
              }}
            />
          </FormItem> */}
          <FormItem {...formItemLayout} required label="查询时间" colon={false}>
            <Space align="baseline">
              <FormItem
                name="selectTimeStart"
                dependencies={['selectTimeEnd']}
                rules={[
                  {
                    required: true,
                    validator: (rule, value, callback) => {
                      if (!value) callback('请选择时间');
                      const { selectTimeEnd } = this.state;
                      const num = 1 * 24 * 60 * 60 * 1000;
                      if (selectTimeEnd && selectTimeEnd.diff(moment(value)) > num)
                        callback('时间跨度不能超过一天');
                      callback();
                    },
                  },
                ]}
              >
                <DatePicker
                  style={{ width: '100%' }}
                  disabledDate={this.disabledDateStart}
                  disabledTime={this.disabledTimeStart}
                  format={DATE_HMS}
                  showTime
                  getCalendarContainer={trigger => trigger.parentNode}
                />
              </FormItem>
              <span>-</span>
              <FormItem
                colon={false}
                name="selectTimeEnd"
                dependencies={['selectTimeStart']}
                rules={[
                  {
                    required: true,
                    validator: (rule, value, callback) => {
                      if (!value) callback('请选择时间');
                      const { selectTimeStart } = this.state;
                      const num = 1 * 24 * 60 * 60 * 1000;
                      if (selectTimeStart && moment(value).diff(selectTimeStart) > num)
                        callback(' ');
                      callback();
                    },
                  },
                ]}
              >
                <DatePicker
                  style={{ width: '100%' }}
                  disabledDate={this.disabledDateEnd}
                  disabledTime={this.disabledTimeEnd}
                  format={DATE_HMS}
                  showTime
                  getCalendarContainer={trigger => trigger.parentNode}
                />
              </FormItem>
            </Space>
          </FormItem>
        </Form>
      </Modal>
    );
  }
}
export const AddModal = connect(mapStateToProps)(_AddModal);
